package com.sskj.one.banker;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.hjq.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.common.base.App;
import com.sskj.common.base.HttpData;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.NumberUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.Constans;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.one.R;
import com.sskj.one.WebActivity;
import com.sskj.one.bean.AgreeBean;
import com.sskj.one.bean.AvailableBean;
import com.sskj.one.bean.BankerInfoBean;
import com.sskj.one.component.DaggerUserDataComponent;
import com.sskj.one.mine.PayPwdActivity;
import com.sskj.one.view.BottomDialog;
import com.sskj.one.view.TipDialog;
import com.zzhoujay.richtext.RichText;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/05/21
 */
public class BankerFragment extends BaseFragment<BankerPresenter> {
    @BindView(R.id.smartRefreshView)
    SmartRefreshLayout smartRefreshView;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.iv_doubt)
    ImageView ivDoubt;
    @BindView(R.id.tv_doubt)
    TextView tvDoubt;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_my_equity)
    TextView tvMyEquity;
    @BindView(R.id.tv_percent)
    TextView tvPercent;
    @BindView(R.id.tv_dividend_history)
    TextView tvDividendHistory;
    @BindView(R.id.tv_dividend_balance)
    TextView tv_dividend_balance;
    //可领取分红
    @BindView(R.id.tv_receive)
    TextView tv_receive;
    @BindView(R.id.tv_transfer_out)
    TextView tvTransferOut;
    @BindView(R.id.tv_transfer_in)
    TextView tvTransferIn;
    @BindView(R.id.tv_msg)
    TextView tvMsg;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_team_num)
    TextView tvTeamNum;
    @BindView(R.id.tv_level)
    TextView tvLevel;
    @BindView(R.id.tv_can_in)
    TextView tvCanIn;
    @BindView(R.id.tv_my_rank)
    TextView tvMyRank;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.view_history)
    View view_history;
    @BindView(R.id.view_balance)
    View view_balance;
    //领取分红
    @BindView(R.id.view_to_receive)
    View view_to_receive;
    @Inject
    UserViewModel userViewModel;

    //股池金额是否展示 0 否 1 是
    private int isBankMoneySee;
    //个人占股是否展示 0 否 1 是
    private int isUserMoneySee;

    private UserData userData;

    private String myEquity;//我的股权
    private String usable;
    private String rate;

    private BaseAdapter<BankerInfoBean.DividendListBean> adapter;
    private int page = 1;
    private int size = 15;
    private HashMap<String, Integer> map;

    @Override
    public int getLayoutId() {
        return R.layout.app_fragment_banker;
    }

    @Override
    public BankerPresenter getPresenter() {
        return new BankerPresenter();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (scrollView != null) {
                scrollView.fling(0);
                scrollView.smoothScrollTo(0, 0);
            }
            if (mPresenter != null) {
                page = 1;
                mPresenter.getAgree("faq");
                mPresenter.getBankerInfo(false, page, size);
            }
        }
    }

    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        map = new HashMap<>();
        map.put("1", R.mipmap.head_one);
        map.put("2", R.mipmap.head_two);
        map.put("3", R.mipmap.head_three);
        map.put("4", R.mipmap.head_four);
        map.put("5", R.mipmap.head_five);
        map.put("6", R.mipmap.head_six);
        map.put("7", R.mipmap.head_seven);
        map.put("8", R.mipmap.head_eight);
        map.put("9", R.mipmap.head_nine);
        map.put("10", R.mipmap.head_ten);
        map.put("11", R.mipmap.head_eleven);
        map.put("12", R.mipmap.head_twelve);
        map.put("13", R.mipmap.head_thirteen);
        map.put("14", R.mipmap.head_fourteen);

        recyclerView.setLayoutManager(new LinearLayoutManager(App.INSTANCE));
        adapter = new BaseAdapter<BankerInfoBean.DividendListBean>(R.layout.item_rank, null, recyclerView, true) {
            @Override
            public void bind(ViewHolder holder, BankerInfoBean.DividendListBean item) {
                holder.setText(R.id.tv_number, (holder.getAdapterPosition() + 1) > 9 ? "" + (holder.getAdapterPosition() + 1) : "0" + (holder.getAdapterPosition() + 1))
                        .setVisible(R.id.ll_user, !isEmpty(item.getUpic()) && !isEmpty(item.getNickname()))
                        .setVisible(R.id.tv_mobile, isEmpty(item.getUpic()) || isEmpty(item.getNickname()))
                        .setText(R.id.tv_mobile, item.getMobile())
                        .setText(R.id.tv_fenhong, item.getMoney_display() == 0 ? "******" : item.getPrice())
                        .setText(R.id.tv_name, item.getNickname())
                        .setImageResource(R.id.iv_head, isEmpty(item.getUpic()) ? R.mipmap.app_logo : map.get(item.getUpic()))
                        .setText(R.id.tv_date, item.getAddtime().replace(" ", "\n"));
            }
        };
        ClickUtil.click(300, tvTransferIn, () -> {
            if (userData != null && "0".equals(userData.getIs_set_tpwd())) {
                new TipDialog(getActivity())
                        .setCancel(true)
                        .setContentText("请先设置资金密码")
                        .setListener(dialog -> PayPwdActivity.start(getActivity())).show();
                return;
            }
            if (isEmpty(usable) || isEmpty(rate)) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
            BottomDialog.bankerTransfer(getActivity(), Constans.TRANSFER_IN, usable, rate, (money, pwd) -> {
                mPresenter.tranferIn(money, pwd);
            });
        });
        ClickUtil.click(300, tvTransferOut, () -> {
            if (userData != null && "0".equals(userData.getIs_set_tpwd())) {
                new TipDialog(getActivity())
                        .setCancel(true)
                        .setContentText("请先设置资金密码")
                        .setListener(dialog -> PayPwdActivity.start(getActivity())).show();
                return;
            }
            if (isEmpty(myEquity) || isEmpty(rate)) {
                ToastUtils.show("获取用户信息失败");
                return;
            }
            BottomDialog.bankerTransfer(getActivity(), Constans.TRANSFER_OUT, myEquity, rate, (money, pwd) -> {
                new TipDialog(getActivity())
                        .setContentText("转出后当前累计佣金等级清零，重新进入股池佣金等级重新计算！")
                        .setCancel(true)
                        .setListener(dialog -> {
                            mPresenter.transferOut(pwd);
                        }).show();
            });
        });
        ClickUtil.click(300, view_history, () -> {
            DividendActivity.start(getActivity(), Constans.DIVIDEND_HISTORY);
        });
        ClickUtil.click(300, view_balance, () -> {
            DividendActivity.start(getActivity(), Constans.DIVIDEND_TODY);
        });
        //领取分红
        ClickUtil.click(300, view_to_receive, () -> {
            mPresenter.getAvailableFenhong();
        });
        ClickUtil.click(300, tvDoubt, () -> {
            WebActivity.start(getActivity(), "law_agree");
        });
    }

    @Override
    public void initData() {
        mPresenter.getBankerInfo(true, page, size);
        mPresenter.getAgree("faq");
        smartRefreshView.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getBankerInfo(false, page, size);
        });
        smartRefreshView.setOnLoadMoreListener(refreshLayout -> {
            page++;
            mPresenter.getBankerInfo(false, page, size);
        });

    }

    public static BankerFragment newInstance() {
        BankerFragment fragment = new BankerFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @SuppressLint("SetTextI18n")
    public void getBankInfoOK(BankerInfoBean data) {
        if (data == null) {
            return;
        }
        isUserMoneySee = data.getPerson_pool_money_start();
        isBankMoneySee = data.getTotal_pool_money_start();
        tvMyRank.setText("（我的今日排名" + data.getPaiming() + "名）");
        tvTeamNum.setText(data.getTeam_num() + "人");
        tvTotalMoney.setText("$" + data.getKyprice());
        tvLevel.setText(data.getLevel().equals("0") ? "V0" : data.getLevel());
        tvCanIn.setText("$" + data.getTopmoney());
        myEquity = NumberUtil.keep(data.getMy_pool().getPool_money(), 5);
        usable = data.getUsable();
        rate = data.getDilution_ratio();
        if (isUserMoneySee == 0) {
            tvPercent.setText("******");
        } else {
            tvPercent.setText(NumberUtil.keep2(data.getMy_pool().getShare_ratio()) + "%");
        }
        if (isBankMoneySee == 0) {
            tvMoney.setText("******");
        } else {
            tvMoney.setText(NumberUtil.keep(data.getShare_pool(), 5));
        }

        tvMyEquity.setText("$" + NumberUtil.keep(data.getMy_pool().getPool_money(), 5));
        tv_dividend_balance.setText(NumberUtil.keep(data.getLave_fenhong(), 5));
        tv_receive.setText(NumberUtil.keep(data.getAvailable_fenhong(), 5));
        tvDividendHistory.setText(NumberUtil.keep(data.getHistorical_dividendt(), 5));
        if (adapter != null) {
            if (page == 1) {
                adapter.setNewData(data.getDividend_list());
            } else {
                adapter.addData(data.getDividend_list());
            }
        }
    }

    public void stopRefresh() {
        if (smartRefreshView != null) {
            smartRefreshView.finishRefresh();
            smartRefreshView.finishLoadMore();
        }
    }

    public void getAgreeOK(AgreeBean data) {
        if (data == null) {
            return;
        }
        if (tvMsg != null) {
            RichText.fromHtml(formatImg(data.getInc_type())).into(tvMsg);
        }
    }

    private String formatImg(String law_agree) {
        Document document = Jsoup.parse(law_agree);
        Elements imgs = document.getElementsByTag("img");
        for (Element img : imgs) {
            img.attr("width", "100%").attr("height", "auto");
            String url = img.attr("src");
            if (!url.contains("http")) {
                url = BaseHttpConfig.BASE_URL + url;
            }
            img.attr("src", url);
        }
        return document.toString();
    }

    public void getAvailableFenhongOK(AvailableBean data) {
        if (data == null) {
            return;
        }
        showReceiveDialog(data);
    }

    private void showReceiveDialog(AvailableBean data) {
        MaterialDialog dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.lib_dialog_receive, false)
                .autoDismiss(true)
                .cancelable(false)
                .show();
        View customView = dialog.getCustomView();
        TextView tv_dividend_yesterday = customView.findViewById(R.id.tv_dividend_yesterday);
        TextView tv_dividend = customView.findViewById(R.id.tv_dividend);
        TextView tv_dividend_usable = customView.findViewById(R.id.tv_dividend_usable);
        tv_dividend_yesterday.setText("$ " + data.getYesterday_yongjin());
        tv_dividend.setText("$ " + data.getLave_fenhong());
        tv_dividend_usable.setText("$ " + data.getAvailable_fenhong());
        ClickUtil.click(300, customView.findViewById(R.id.tv_cancel), dialog::dismiss);
        ClickUtil.click(300, customView.findViewById(R.id.tv_confirm), () -> {
            mPresenter.lingqu();
            dialog.dismiss();
        });
        dialog.show();
    }
}
